<?php
/* $Id$ */
/*
	diag_backup.php

    Copyright (C) 2009 Wang Zhongliang <wzlsh629@163.com>.
    All rights reserved.

	Copyright (C) 2004,2005,2006 Scott Ullrich
	All rights reserved.

	originally part of m0n0wall (http://m0n0.ch/wall)
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.
*/

##|+PRIV
##|*IDENT=page-diagnostics-backup/restore
##|*NAME=Diagnostics: Backup/restore page
##|*DESCR=Allow access to the 'Diagnostics: Backup/restore' page.
##|*MATCH=diag_backup.php*
##|-PRIV


/* Allow additional execution time 0 = no limit. */
ini_set('max_execution_time', '3600');
ini_set('max_input_time', '3600');

/* omit no-cache headers because it confuses IE with file downloads */
$omit_nocacheheaders = true;
require("guiconfig.inc");

function remove_bad_chars($string) {
	return preg_replace('/[^a-z|_|0-9]/i','',$string);
}

function check_and_returnif_section_exists($section) {
	global $config;
	if(is_array($config[$section]))
		return true;
	return false;
}

function spit_out_select_items($area, $showall) {
	global $config;
		
	$areas = array("aliases" => "Aliases", 
//				   "captiveportal" => "Captive Portal",
				   "dnsmasq" => "DNS Forwarder",				
				   "dhcpd" => "DHCP Server",
				   "filter" => "Firewall Rules",
				   "interfaces" => "Interfaces",
//				   "ipsec" => "IPSEC",
				   "nat" => "NAT",
//				   "ovpn" => "OpenVPN",
//				   "installedpackages" => "Package Manager",
				   "pptpd" => "PPTP Server",
				   "cron" => "Scheduled Tasks",				
				   "syslog" => "Syslog",
				   "system" => "System",
				   "staticroutes" => "Static routes",
				   "sysctl" => "System tunables",
				   "snmpd" => "SNMP Server",
				   "shaper" => "Traffic Shaper",
				   "vlans" => "VLANS",
//				   "wol" => "Wake on LAN"
	);

	$select  = "<select name=\"{$area}\">\n";
	$select .= "<option VALUE=\"\">ALL</option>";

	if($showall == true) 
		foreach($areas as $area => $areaname)
			$select .= "<option value='{$area}'>{$areaname}</option>\n";
	else 
		foreach($areas as $area => $areaname)
			if(check_and_returnif_section_exists($area) == true)
				$select .= "<option value='{$area}'>{$areaname}</option>\n";

	$select .= "</select>\n";
		
//	echo $select;

}

if ($_POST) {
	unset($input_errors);
	if (stristr($_POST['Submit'], "还原"))
		$mode = "restore";
	else if (stristr($_POST['Submit'], "Reinstall"))
		$mode = "reinstallpackages";
	else if (stristr($_POST['Submit'], "下载"))
		$mode = "download";
	else if (stristr($_POST['Submit'], "Restore version"))
		$mode = "restore_ver";

//	if ($_POST["nopackages"] <> "")
//		$options = "nopackages";

	$_POST['donotbackuprrd'] = 1;
		
	if ($_POST["ver"] <> "")
		$ver2restore = $_POST["ver"];

	if ($mode) {

		if ($mode == "download") {

			if ($_POST['encrypt']) {
				if(!$_POST['encrypt_password'] || !$_POST['encrypt_passconf'])
					$input_errors[] = "请输入密码。";
				if($_POST['encrypt_password'] != $_POST['encrypt_passconf'])
					$input_errors[] = "两次密码输入不同。";
			}

			if (!$input_errors) {

				config_lock();

				$host = "{$config['system']['hostname']}.{$config['system']['domain']}";
				$name = "config-{$host}-".date("YmdHis").".xml";
				$data = "";

				if($options == "nopackages") {
					$sfn = "/tmp/config.xml.nopkg";
					exec("sed '/<installedpackages>/,/<\/installedpackages>/d' /conf/config.xml > {$sfn}");
					$data = file_get_contents($sfn);
				} else {
					if(!$_POST['backuparea']) {
						/* backup entire configuration */
						$data = file_get_contents("{$g['conf_path']}/config.xml");
					} else {
						/* backup specific area of configuration */
						$data = backup_config_section($_POST['backuparea']);
						$name = "{$_POST['backuparea']}-{$name}";
					}
				}

				if ($_POST['encrypt']) {
					$data = encrypt_data($data, $_POST['encrypt_password']);
					tagfile_reformat($data, $data, "config.xml");
				}

				/* 
				 *  Backup RRD Data
				 */
				if(!$_POST['donotbackuprrd']) {
					$data = str_replace("</pfsense>", "\t<rrddata>", $data);
					$rrd_files_var_db_rrd = split("\n",`cd /var/db/rrd && ls *.rrd`);
					foreach($rrd_files_var_db_rrd as $rrd) {
						if($rrd) {
							$rrd_data = file_get_contents("{$g['vardb_path']}/rrd/{$rrd}");
							if($rrd_data) {
								$data .= "\t\t<rrddatafile>\n";
								$data .= "\t\t\t<filename>{$rrd}</filename>\n";
								$data .= "\t\t\t<data>" . base64_encode($rrd_data) . "</data>\n";
								$data .= "\t\t</rrddatafile>\n";
							}
						}
					}
					$data .= "\t</rrddata>\n";
					$data .= "</pfsense>\n";
				}
				
				$size = strlen($data);
				header("Content-Type: application/octet-stream");
				header("Content-Disposition: attachment; filename={$name}");
				header("Content-Length: $size");
				echo $data;

				config_unlock();
				exit;
			}
		}

		if ($mode == "restore") {

			if ($_POST['decrypt']) {
				if(!$_POST['decrypt_password'] || !$_POST['decrypt_passconf'])
					$input_errors[] = "请输入密码。";
				if($_POST['decrypt_password'] != $_POST['decrypt_passconf'])
					$input_errors[] = "两次密码输入不同。";
			}

			if (!$input_errors) {

				if (is_uploaded_file($_FILES['conffile']['tmp_name'])) {

					/* read the file contents */
					$data = file_get_contents($_FILES['conffile']['tmp_name']);
					if(!$data) {
						log_error("Warning, could not read file " . $_FILES['conffile']['tmp_name']);
						return 1;
					}

					if ($_POST['decrypt']) {
						if (!tagfile_deformat($data, $data, "config.xml")) {
							$input_errors[] = "上传文件中不包含加密过的配置文件。";
							return 1;
						}
						$data = decrypt_data($data, $_POST['decrypt_password']);
					}

					if(stristr($data, "m0n0wall")) {
						log_error("Upgrading m0n0wall configuration to pfsense.");
						/* m0n0wall was found in config.  convert it. */
						$data = str_replace("m0n0wall", "pfsense", $data);
						$m0n0wall_upgrade = true;
					}

					if($_POST['restorearea']) {
						/* restore a specific area of the configuration */
						if(!stristr($data, $_POST['restorearea'])) {
							$input_errors[] = "无法定位正确的XML标签。";
						} else {
							restore_config_section($_POST['restorearea'], $data);
							filter_configure();
							$savemsg = "配置文件已还原。请重启机器。";
						}
					} else {
						if(!stristr($data, "<stairway>")) {
							$input_errors[] = "无法定位正确的XML标签。";
						} else {
							/* restore the entire configuration */
							file_put_contents($_FILES['conffile']['tmp_name'], $data);
							if (config_install($_FILES['conffile']['tmp_name']) == 0) {
								/* this will be picked up by /index.php */
								conf_mount_rw();
								if($g['platform'] <> "cdrom")
									touch("/needs_package_sync");
								$reboot_needed = true;
								$savemsg = "配置文件已还原。正在重启机器……";
								/* remove cache, we will force a config reboot */
								if(file_exists("/tmp/config.cache"))
									unlink("/tmp/config.cache");
								$config = parse_config(true);
								/* extract out rrd items, unset from $confgi when done */
								if($config['rrddata']) {
									foreach($config['rrddata']['rrddatafile'] as $rrd) {
										$rrd_fd = fopen("{$g['vardb_path']}/rrd/{$rrd['filename']}", "w");
										fwrite($rrd_fd, base64_decode($rrd['data']));
										fclose($rrd_fd);
									}
									unset($config['rrddata']);
									unlink_if_exists("/tmp/config.cache");
									write_config();
									conf_mount_ro();
								}
								if($m0n0wall_upgrade == true) {
									if($config['system']['gateway'] <> "")
										$config['interfaces']['wan']['gateway'] = $config['system']['gateway'];
									unset($config['shaper']);
									/* optional if list */
									$ifdescrs = get_configured_interface_list(true, true);
									/* remove special characters from interface descriptions */
									if(is_array($ifdescrs))
										foreach($ifdescrs as $iface)
											$config['interfaces'][$iface]['descr'] = remove_bad_chars($config['interfaces'][$iface]['descr']);
									unlink_if_exists("/tmp/config.cache");
									write_config();
									conf_mount_ro();
									$savemsg = "The m0n0wall configuration has been restored and upgraded to pfSense.<p>The firewall is now rebooting.";
									$reboot_needed = true;
								}
								if(isset($config['captiveportal']['enable'])) {
									/* for some reason ipfw doesn't init correctly except on bootup sequence */
									$savemsg = "配置文件已还原。正在重启机器……";
									$reboot_needed = true;
								}
								setup_serial_port();
								if(is_interface_mismatch() == true) {
									touch("/var/run/interface_mismatch_reboot_needed");
									$reboot_needed = false;
									header("Location: interfaces_assign.php");
									exit;
								}
							} else {
								$input_errors[] = "无法还原该配置文件";
							}
						}
					}
				} else {
					$input_errors[] = "无法还原该配置文件（上传文件错误）。";
				}
			}
		}

		if ($mode == "reinstallpackages") {

			header("Location: pkg_mgr_install.php?mode=reinstallall");
			exit;
                } else if ($mode == "restore_ver") {
			$input_errors[] = "XXX - this feature may hose your config (do NOT backrev configs!) - billm";
			if ($ver2restore <> "") {
				$conf_file = "{$g['cf_conf_path']}/bak/config-" . strtotime($ver2restore) . ".xml";
                                if (config_install($conf_file) == 0) {
									$reboot_needed = true;
                                    $savemsg = "The configuration has been restored. The firewall is now rebooting.";
                                } else {
                                	$input_errors[] = "The configuration could not be restored.";
                                }
                        } else {
                                $input_errors[] = "No version selected.";
                        }
		}
	}
}

$id = rand() . '.' . time();

$mth = ini_get('upload_progress_meter.store_method');
$dir = ini_get('upload_progress_meter.file.filename_template');

$pgtitle = array("系统工具","备份/还原");
include("head.inc");

?>

<body link="#0000CC" vlink="#0000CC" alink="#0000CC">
<?php include("fbegin.inc"); ?>
<script language="JavaScript">
<!--

function encrypt_change() {

	if (!document.iform.encrypt.checked)
		document.getElementById("encrypt_opts").style.display="none";
	else
		document.getElementById("encrypt_opts").style.display="";
}

function decrypt_change() {

	if (!document.iform.decrypt.checked)
		document.getElementById("decrypt_opts").style.display="none";
	else
		document.getElementById("decrypt_opts").style.display="";
}

//-->
</script>
<form action="diag_backup.php" method="post" name="iform" enctype="multipart/form-data">
<?php if ($input_errors) print_input_errors($input_errors); ?>
<?php if ($savemsg) print_info_box($savemsg); ?>
<div class="soft_cont_right_table">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
	<tr>
		<td>
<?php
		$tab_array = array();
		$tab_array[0] = array("历史配置", false, "diag_confbak.php");
		$tab_array[1] = array("备份/还原", true, "diag_backup.php");
		display_top_tabs($tab_array);
?>
		</td>
	</tr>
	<tr>
		<td>
			<div id="mainarea">
			<table class="tabcont" align="center" width="100%" border="0" cellpadding="6" cellspacing="0">
				<tr>
					<td colspan="2" class="listtopic">备份</td>
				</tr>
				<tr>
					<td width="22%" valign="baseline" class="vncell">&nbsp;</td>
					<td width="78%" class="vtable">
						<p>点击下载XML配置文件<br /><br /></p>
						<table>
							<tr>
								<td>
									<input name="encrypt" type="checkbox" class="formcheckbox" id="nopackages" onClick="encrypt_change()">
								</td>
								<td>
									<span class="vexpl">是否加密</span>
								</td>
							</tr>
						</table>
						<table id="encrypt_opts">
							<tr>
								<td>
									<span class="vexpl">密码：</span>
								</td>
								<td>
									<input name="encrypt_password" type="password" class="formfld pwd" size="20" value="" />
								</td>
							</tr>
							<tr>
								<td>
									<span class="vexpl">密码确认：</span>
								</td>
								<td>
									<input name="encrypt_passconf" type="password" class="formfld pwd" size="20" value="" />
								</td>
							</tr>
						</table>
						<p><input name="Submit" type="submit" class="formbtn" id="download" value="下载"></p>
					</td>
				</tr>
				<tr>
					<td colspan="2" class="list" height="12">&nbsp;</td>
                </tr>
                <tr>
					<td colspan="2" class="listtopic">还原</td>
				</tr>
				<tr>
					<td width="22%" valign="baseline" class="vncell">&nbsp;</td>
					<td width="78%" class="vtable">
						上传<?=$g['[product_name']?> XML配置文件并还原<br /><br />
						<p><input name="conffile" type="file" class="formfld unknown" id="conffile" size="40"></p>
						<table>
							<tr>
								<td>
									<input name="decrypt" type="checkbox" class="formcheckbox" id="nopackages" onClick="decrypt_change()">
								</td>
								<td>
									<span class="vexpl">是否加密</span>
								</td>
							</tr>
						</table>
						<table id="decrypt_opts">
							<tr>
								<td>
									<span class="vexpl">密码：</span>
								</td>
								<td>
									<input name="decrypt_password" type="password" class="formfld pwd" size="20" value="" />
								</td>
							</tr>
							<tr>
								<td>
									<span class="vexpl">密码确认：</span>
								</td>
								<td>
									<input name="decrypt_passconf" type="password" class="formfld pwd" size="20" value="" />
								</td>
							</tr>
						</table>
						<p><input name="Submit" type="submit" class="formbtn" id="restore" value="还原"></p>
                      	<p><strong><span class="red">注意：</span></strong><br />您可能需要重启机器使还原的配置生效。<br /></p>
					</td>
				</tr>
				<?php if($config['installedpackages']['package'] != "") { ?>
				<tr>
					<td colspan="2" class="list" height="12">&nbsp;</td>
				</tr>
				<tr>
					<td colspan="2" class="listtopic">Reinstall packages</td>
				</tr>
				<tr>
					<td width="22%" valign="baseline" class="vncell">&nbsp;</td>
					<td width="78%" class="vtable">
						<p>Click this button to reinstall all system packages.  This may take a while. <br /><br />
		  				<input name="Submit" type="submit" class="formbtn" id="reinstallpackages" value="Reinstall packages">
					</td>
				</tr>
				<?php } ?>
			</table>
			</div>
		</td>
	</tr>
</table>
</div>
</form>

<script language="JavaScript">
<!--
encrypt_change();
decrypt_change();
//-->
</script>

<?php include("fend.inc"); ?>
</body>
</html>

<?php

if($reboot_needed == true) {
	ob_flush();
	flush();
	sleep(5);
	while(file_exists("{$g['varrun_path']}/config.lock"))
		sleep(3);
	mwexec("/sbin/shutdown -r now");
	exit;
}

?>
